class Router {
  constructor(onFail, onResponse, onError) {
    this.onFail = onFail;
    this.onResponse = onResponse;
    this.onError = onError;
    this.routes = [];
  }

  register(regularExpressions, method, service) {
    let status = 0;
    this.routes.forEach((route) => {
      if (route.re.toString() === regularExpressions.toString() && route.method === method) {
        status = 1;
      }
    })
    if (status !== 1) {
      this.routes.push({re: regularExpressions, method: method, service: service});
    }
  }

  delete(regularExpressions, method) {
    this.routes.find((route, index) => {
      new Promise((resolve, reject) => {
        route.re.toString() === regularExpressions.toString() && route.method === method ? resolve() : reject();
      }).then(
          () => {
            this.routes.splice(index, 1);
          }
          , () => {

          }
      ).catch((error) => {
        throw new Error(error);
      })
    })
  }

  test(request, response) {
    let result = null;
    this.routes.find((route) => {
      if(route.re.test(request.url)){
        if(route.method === request.method){
          result = route;
        }
      }
    })
    result ? result.service(request,response,this.onResponse,this.onError) : this.onFail(request,response,this.onResponse,this.onError);
  }
}

module.exports = Router;